//
//  AppDelegate+AppService.m
//  MiAiApp
//
//  Created by voidcat on 2017/5/19.
//  Copyright © 2017年 voidcat. All rights reserved.
//

#import "AppDelegate+AppService.h"
#import <UMSocialCore/UMSocialCore.h>
#import "LoginViewController.h"
#import "AdPageView.h"
#import "RootWebViewController.h"
#import "OpenUDID.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WXApiManager.h"

@implementation AppDelegate (AppService)
#pragma mark ————— 初始网络请求库 —————
-(void)initYTKNetWork
{
    YTKNetworkConfig *netConfig = [YTKNetworkConfig sharedConfig];
    netConfig.baseUrl = URL_main;
    NSLog(@"%@", URL_main);
    netConfig.cdnUrl = URL_main;
    netConfig.debugLogEnabled = YES;
}

#pragma mark ————— 初始化键盘 —————
-(void)initKeyBoard
{
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].toolbarDoneBarButtonItemText = ASLocalizedString(@"完成");
}

#pragma mark ————— 初始化服务 —————
-(void)initService{
    //注册登录状态监听
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loginStateChange:)
                                                 name:KNotificationLoginStateChange
                                               object:nil];
    
    //网络状态监听
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(netWorkStateChange:)
                                                 name:KNotificationNetWorkStateChange
                                               object:nil];
    
    //[[HUDHelper sharedInstance] loading:ASLocalizedString(@"初始化数据中..")];
    //初始化config变量
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self initConfig];
    });
    
    //注册微信支付
    //向微信注册,发起支付必须注册
    [WXApi registerApp:kAppKey_Wechat enableMTA:YES];
}

-(void)initHeartbeat
{
    if(self.heartbeat == nil)
    {
        //        self.heartbeat = [NSTimer scheduledTimerWithTimeInterval:[KGlobalVariable.appmodel.heartbeat intValue] target:self selector:@selector(doHeartbeat) userInfo:nil repeats:YES];
        
        self.heartbeat = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(doHeartbeat) userInfo:nil repeats:YES];
        
    }
}

-(void)doHeartbeat
{
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"app_api" A:@"interval"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    //[param setObject:@"" forKey:@""];
    
    [CYNET POST:url parameters:param responseCache:^(id responseObject) {
        NSLog(@"%@", ASLocalizedString(@"================心跳"));
    } success:^(id responseObject) {
        
    } failure:^(NSString *error) {
        BOOL loadStatus = [[UserManager sharedUserManager] loadUserInfo];
        NSLog(ASLocalizedString(@"================心跳2%d"),loadStatus);
        
        //        [MBProgressHUD showTopTipMessage:error];
    } hasCache:NO];
}

//定位
-(void)initLocation
{
    //判断定位功能是否打开
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationmanager = [[CLLocationManager alloc]init];
        self.locationmanager.delegate = self;
        [self.locationmanager requestAlwaysAuthorization];
        self.currentCity = [NSString new];
        [self.locationmanager requestWhenInUseAuthorization];
        
        //设置寻址精度
        self.locationmanager.desiredAccuracy = kCLLocationAccuracyBest;
        self.locationmanager.distanceFilter = 5.0;
        [self.locationmanager startUpdatingLocation];
    }
}

#pragma mark 定位成功后则执行此代理方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    [self.locationmanager stopUpdatingHeading];
    //旧址
    CLLocation *currentLocation = [locations lastObject];
    CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
    //打印当前的经度与纬度
    NSLog(ASLocalizedString(@"当前的经度与纬度%f,%f"),currentLocation.coordinate.latitude,currentLocation.coordinate.longitude);
    self.strlatitude = NSStringFormat(@"%f",currentLocation.coordinate.latitude);
    self.strlongitude = NSStringFormat(@"%f",currentLocation.coordinate.longitude);
    
    //反地理编码
    [geoCoder reverseGeocodeLocation:manager.location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (placemarks.count > 0) {
            CLPlacemark *placeMark = placemarks[0];
            
            self.currentCity = placeMark.locality;
            
            if(placeMark.locality == nil)
            {
                self.currentCity = placeMark.administrativeArea;
            }
            
            if (!self.currentCity) {
                self.currentCity = ASLocalizedString(@"无法定位当前城市");
            }
            /*看需求定义一个全局变量来接收赋值*/
            NSLog(@"----%@",placeMark.country);//当前国家
            NSLog(@"%@",self.currentCity);//当前的城市
            NSLog(@"%@",placeMark.subLocality);//当前的位置
            //            NSLog(@"%@",placeMark.thoroughfare);//当前街道
            //            NSLog(@"%@",placeMark.name);//具体地址
            
        }
    }];
    
}


#pragma mark CoreLocation delegate (定位失败)
//定位失败后调用此代理方法
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    //设置提示提醒用户打开定位服务
    //    UIAlertController *alert = [UIAlertController alertControllerWithTitle:ASLocalizedString(@"允许定位提示")message:ASLocalizedString(@"请在设置中打开定位")preferredStyle:UIAlertControllerStyleAlert];
    //    UIAlertAction *okAction = [UIAlertAction actionWithTitle:ASLocalizedString(@"打开定位")style:UIAlertActionStyleDefault handler:nil];
    //
    //    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:ASLocalizedString(@"取消")style:UIAlertActionStyleCancel handler:nil];
    //    [alert addAction:okAction];
    //    [alert addAction:cancelAction];
    //    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark ————— 初始化window —————
-(void)initWindow{
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = KWhiteColor;
    [self.window makeKeyAndVisible];
    [[UIButton appearance] setExclusiveTouch:YES];
    //    [[UIButton appearance] setShowsTouchWhenHighlighted:YES];
    [UIActivityIndicatorView appearanceWhenContainedIn:[MBProgressHUD class], nil].color = KWhiteColor;
    if (@available(iOS 11.0, *)){
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }
}


#pragma mark ————— 初始化用户系统 —————
-(void)initUserManager{
    
    
    DLog(ASLocalizedString(@"设备IMEI ：%@"),[OpenUDID value]);
    if([userManager loadUserInfo]){
        
        //如果有本地数据，先展示TabBar 随后异步自动登录
        self.mainTabBar = [MainTabBarController new];
        self.window.rootViewController = self.mainTabBar;
        
        //自动登录
        [userManager autoLoginToServer:^(BOOL success, NSString *des) {
            if (success) {
                DLog(ASLocalizedString(@"自动登录成功"));
                //                    [MBProgressHUD showSuccessMessage:ASLocalizedString(@"自动登录成功")];
                KPostNotification(KNotificationAutoLoginSuccess, nil);
            }else{
                [MBProgressHUD showErrorMessage:NSStringFormat(ASLocalizedString(@"自动登录失败：%@"),des)];
            }
        }];
        
    }else{
        //没有登录过，展示登录页面
        KPostNotification(KNotificationLoginStateChange, @NO)
        //        [MBProgressHUD showErrorMessage:ASLocalizedString(@"需要登录")];
    }
    
    self.welView = [[Login2View alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, kScreenHeight)];
    [kAppWindow addSubview:self.welView];
}

#pragma mark ————— 登录状态处理 —————
- (void)loginStateChange:(NSNotification *)notification
{
    BOOL loginSuccess = [notification.object boolValue];
    
    if (loginSuccess) {//登陆成功加载主窗口控制器
        [self doHeartbeat];
        //为避免自动登录成功刷新tabbar
        if (!self.mainTabBar || ![self.window.rootViewController isKindOfClass:[MainTabBarController class]]) {
            self.mainTabBar = [MainTabBarController new];
            
            CATransition *anima = [CATransition animation];
            anima.type = @"cube";//设置动画的类型
            anima.subtype = kCATransitionFromRight; //设置动画的方向
            anima.duration = 0.3f;
            
            self.window.rootViewController = self.mainTabBar;
            
            [kAppWindow.layer addAnimation:anima forKey:@"revealAnimation"];
            
        }
        
    }else {//登陆失败加载登陆页面控制器
        
        self.mainTabBar = nil;
        RootNavigationController *loginNavi =[[RootNavigationController alloc] initWithRootViewController:[LoginViewController new]];
        
        CATransition *anima = [CATransition animation];
        anima.type = @"fade";//设置动画的类型
        anima.subtype = kCATransitionFromRight; //设置动画的方向
        anima.duration = 0.3f;
        
        self.window.rootViewController = loginNavi;
        
        [kAppWindow.layer addAnimation:anima forKey:@"revealAnimation"];
        
    }
    //展示FPS
    //    [AppManager showFPS];
}


#pragma mark ————— 网络状态变化 —————
- (void)netWorkStateChange:(NSNotification *)notification
{
    BOOL isNetWork = [notification.object boolValue];
    
    if (isNetWork) {//有网络
        [self initConfig];
        if ([userManager loadUserInfo] && !isLogin) {//有用户数据 并且 未登录成功 重新来一次自动登录
            [userManager autoLoginToServer:^(BOOL success, NSString *des) {
                if (success) {
                    DLog(ASLocalizedString(@"网络改变后，自动登录成功"));
                    //                    [MBProgressHUD showSuccessMessage:ASLocalizedString(@"网络改变后，自动登录成功")];
                    KPostNotification(KNotificationAutoLoginSuccess, nil);
                }else{
                    [MBProgressHUD showErrorMessage:NSStringFormat(ASLocalizedString(@"自动登录失败：%@"),des)];
                }
            }];
        }
        
    }else {//登陆失败加载登陆页面控制器
        [MBProgressHUD showTopTipMessage:ASLocalizedString(@"网络状态不佳")isWindow:YES];
    }
}


#pragma mark ————— 友盟 初始化 —————
-(void)initUMeng{
    /* 打开调试日志 */
    [[UMSocialManager defaultManager] openLog:YES];
    
    /* 设置友盟appkey */
    [[UMSocialManager defaultManager] setUmSocialAppkey:UMengKey];
    
    [self configUSharePlatforms];
}
#pragma mark ————— 配置第三方 —————
-(void)configUSharePlatforms{
    /* 设置微信的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:kAppKey_Wechat appSecret:kSecret_Wechat redirectURL:nil];
    /*
     * 移除相应平台的分享，如微信收藏
     */
    //[[UMSocialManager defaultManager] removePlatformProviderWithPlatformTypes:@[@(UMSocialPlatformType_WechatFavorite)]];
    
    /* 设置分享到QQ互联的appID
     * U-Share SDK为了兼容大部分平台命名，统一用appKey和appSecret进行参数设置，而QQ平台仅需将appID作为U-Share的appKey参数传进即可。
     */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:kAppKey_Tencent/*设置QQ平台的appID*/  appSecret:nil redirectURL:nil];
}

#pragma mark ————— OpenURL 回调 —————
// 支持所有iOS系统
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
    if (!result) {
        // 其他如支付等SDK的回调
        
        if ([url.host isEqualToString:@"safepay"]) {
            // 支付跳转支付宝钱包进行支付，处理支付结果
            [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
                NSLog(@"result = %@",resultDic);
                [self AlipayWithResutl:resultDic];
            }];
            
        }
        else
        {
            return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
        }
        
    }
    return result;
}

#pragma mark ————— 网络状态监听 —————
- (void)monitorNetworkStatus
{
    // 网络状态改变一次, networkStatusWithBlock就会响应一次
    [PPNetworkHelper networkStatusWithBlock:^(PPNetworkStatusType networkStatus) {
        
        switch (networkStatus) {
                // 未知网络
            case PPNetworkStatusUnknown:
                DLog(ASLocalizedString(@"网络环境：未知网络"));
                // 无网络
            case PPNetworkStatusNotReachable:
                DLog(ASLocalizedString(@"网络环境：无网络"));
                KPostNotification(KNotificationNetWorkStateChange, @NO);
                break;
                // 手机网络
            case PPNetworkStatusReachableViaWWAN:
                DLog(ASLocalizedString(@"网络环境：手机自带网络"));
                // 无线网络
            case PPNetworkStatusReachableViaWiFi:
                DLog(ASLocalizedString(@"网络环境：WiFi"));
                KPostNotification(KNotificationNetWorkStateChange, @YES);
                break;
        }
        
        //网络变化时重新加载配置
        if(networkStatus == PPNetworkStatusReachableViaWWAN || networkStatus == PPNetworkStatusReachableViaWiFi)
        {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self initConfig];
            });
            
        }
        
    }];
    
}




// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    BOOL result = [[UMSocialManager defaultManager]  handleOpenURL:url options:options];
    
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        //这个是进程KILL掉之后也会调用，这个只是第一次授权回调，同时也会返回支付信息
        [[AlipaySDK defaultService]processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            [self AlipayWithResutl:resultDic];
        }];
        //跳转支付宝钱包进行支付，处理支付结果，这个只是辅佐订单支付结果回调
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            [self AlipayWithResutl:resultDic];
        }];
        
        [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
        
    }
    return YES;
}

-(void)AlipayWithResutl:(NSDictionary *)resultDic{
    NSString  *str = [resultDic objectForKey:@"resultStatus"];
    if (str.intValue == 9000)
    {
        [HUDHelper alert:ASLocalizedString(@"支付成功")];
        // 支付成功
        //通过通知中心发送通知
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PayResult" object:@"ali_success" userInfo:nil];
    }
    else
    {
        [HUDHelper alert:ASLocalizedString(@"支付失败")];
        //通过通知中心发送通知
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PayResult" object:@"fail" userInfo:nil];
    }
    
}


//初始化网络配置

-(void)initConfig
{
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"app_api" A:@"config"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    //[param setObject:@"" forKey:@""];
    
    [CYNET POST:url parameters:param responseCache:^(id responseObject) {
        
    } success:^(id responseObject) {
        
        //        [self.welView dismissViewControllerAnimated:NO completion:nil];
        
        
        
        [MBProgressHUD hideHUD];
        KGlobalVariable.appmodel = [AppConfig modelWithDictionary:responseObject];
        NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"YeyingBuild"];
        NSString *newVersion = KGlobalVariable.appmodel.ios_version;
        if (![currentVersion isEqualToString:newVersion]) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"版本更新" message:@"请更新app版本" preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/mapi/public/index.php/api/download_api/index?invite_code=%@",URL_main,curUser.id]];
                [[UIApplication sharedApplication] openURL:url];
            }]];
            [self.window.rootViewController presentViewController:alert animated:YES completion:nil];
        }
        
        
      
        KPostNotification(KinitConfigLoginSuccess, nil);
        
        
        if(StrValid(KGlobalVariable.appmodel.splash_img_url))
        {
            //加载广告
//            AdPageView *adView = [[AdPageView alloc] initWithFrame:kScreen_Bounds withTapBlock:^{
//                RootNavigationController *loginNavi =[[RootNavigationController alloc] initWithRootViewController:[[RootWebViewController alloc] initWithUrl:KGlobalVariable.appmodel.splash_url]];
//                [kRootViewController presentViewController:loginNavi animated:YES completion:nil];
//            }];
        }
        
        
        //更新sdkappid
        if(StrValid(KGlobalVariable.appmodel.sdkappid))
        {
            curUser.sdkappid = KGlobalVariable.appmodel.sdkappid;
        }
        
        //    //初始化IM
        [[IMManager sharedIMManager] initIM];
        [[IMManager sharedIMManager] IMLogin:@"" IMPwd:@"" completion:^(BOOL success, NSString *des) {
            
        }];
        
        //初始化心跳 TIM监听用不到了
//        [self initHeartbeat];
    } failure:^(NSString *error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //加载失败的话重新加载
            [self initConfig];
        });
    } hasCache:NO];
}

+ (AppDelegate *)shareAppDelegate{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}


-(UIViewController *)getCurrentVC{
    
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}

-(UIViewController *)getCurrentUIVC
{
    UIViewController  *superVC = [self getCurrentVC];
    
    if ([superVC isKindOfClass:[UITabBarController class]]) {
        
        UIViewController  *tabSelectVC = ((UITabBarController*)superVC).selectedViewController;
        
        if ([tabSelectVC isKindOfClass:[UINavigationController class]]) {
            
            return ((UINavigationController*)tabSelectVC).viewControllers.lastObject;
        }
        return tabSelectVC;
    }else
        if ([superVC isKindOfClass:[UINavigationController class]]) {
            
            return ((UINavigationController*)superVC).viewControllers.lastObject;
        }
    return superVC;
}


@end

